import Taro, { Component } from '@tarojs/taro'
import {View, Button, Text, Input, Icon, ScrollView} from '@tarojs/components'
import './hotSearchPage.scss'
import { AtIcon ,AtTabs, AtTabsPane,AtTabBar } from 'taro-ui'
import searchStorage from "../../storage/searchStorage";
import arrayUtil from "../../utils/arrayUtil";
import store from '../../store/hotSearchStore';
import AppConfig from '../../config/appConfig';
import Recommend from '../../components/recommend/recommend';
import viewUtil from '../../utils/viewUtil';
import taroUtils from '../../utils/taroUtils';
import {NumToPx,IsNullObject} from '../../utils/utils';
import appStore from "../../store/appStore";

class HotSearchPage extends Component{

  config = {
    navigationBarTitleText: '搜索',
    "disableScroll": true   //静止页面滚动
  }

  constructor(props) {
    super(props);
    this.state={
      value:'',
      renderPage1:true,
      history: [],
      scrollviewHeight:'0px',
      searchType1: AppConfig.TaoBao, // 搜索类型(淘宝，京东，拼度多)
      searchType2: AppConfig.ZhongHe, //（综合，价格。。。）
      currentSearch2 :AppConfig.ZhongHe ,//(为searchType2服务)

      curPriceSearch:AppConfig.PriceHeight,
      curSaleSearch:AppConfig.SalesHeight,

      searchData:[],   //数据
      pageIndex:1, //分页申请第几页
      searchScrollviewHeight:0,
    }

    this.getHistoryData()
    store.applyKeyWords()
  }

  componentWillMount () {
  }

  componentDidMount () {

    if (IsNullObject(this.$router.params.searchText) === false){
      this.setState({
        value:this.$router.params.searchText
      },()=>{
        this.onConfirm({detail:{value: this.$router.params.searchText}})
      })

    }else {
      //  自动启动搜索
      this.refs.hotInput.focus = true;

    }
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }


  getHistoryData = () => {
     this.setState({
       history:searchStorage.get(),
       scrollviewHeight: searchStorage.get() === null ? '0px' : '120px',
     })
  };

  /**
   * 清空input
   * */
  onClear=()=>{
    this.setState({
      value:''
    })
  }

  /**
   * 点击input 取消
   * */
  onCancel=()=>{
    this.refs.hotInput.focus = false;
  }

  /**
   * 点击input 搜索
   * */
  onSearch=()=>{
    this.onConfirm({detail:{value: this.state.value}})

  }

  /**
   * 输入
   * */
  onInput=(e)=>{
    this.setState({
      value:e.detail.value
    })
  }
  /**
   * 输入确定
   * */
  onConfirm=(e)=>{

    if (e.detail.value === ''){
      viewUtil.ShowToast('不能为空～～')
      return
    }

    let temp = this.state.history
    if (Array.isArray(temp) === false){
      temp=[]
    }
    //存在就删除
    if (temp.includes(e.detail.value) === true) {
      temp = arrayUtil.Remove(temp, e.detail.value);
    }

    //添加到头
    temp.unshift(e.detail.value);
    //限制个数
    if (temp.length > 20) {
      temp.pop();
    }
    searchStorage.save(temp)
    this.getHistoryData()
    this.sendSuperSearch(e.detail.value)
  }

  /**
   * 发送网格请求获取数据
   * */
  sendSuperSearch(text){
    if (IsNullObject(this.refs.RefRecommend) === false)
      this.refs.RefRecommend.ScrollTop()
      store.getSuperSearch(this.state.searchType1,this.state.searchType2,text,1).then(res=>{
        this.setState({
          renderPage1: false,
          searchData:res.data,
          pageIndex:res.pageIndex
        });
    })

  }

  /**
   * 点击历史item
   * */
  onClickHistoryItem(item){
    this.setState({
      value: item,
    },()=>{
      this.onSearch()
    });
  }


  /**
   * 点击清空历史
   * */
  onClickClearHot=()=>{

    Taro.showModal({
      title: '删除',
      content: '是否删除历史纪录?',
    })
      .then(res => {
        if (res.confirm){
          searchStorage.clear()
          this.setState({
            history: [],
            scrollviewHeight: '0px',
          })
        }
      })
  }

  /**
   * 点击热搜item
   * */
  onClickHotItem(item){
    // console.log(item)
    // this.setState({
    //   value: item,
    // });
    this.onClickHistoryItem(item)
  }

  /**
   * 点击选择淘宝，京东,拼多多
   * */
  onClickChosePage (value) {
    this.setState({
      searchType1: value
    },
      () => {
        this.sendSuperSearch(this.state.value)
      })
  }
  /**
   * 点击选择综合，价格...
   * */
  onClickSecond(value){
    let t = value
    let t1 = this.state.curPriceSearch
    let t2 = this.state.curSaleSearch
    if (value ===2){
      const lastValue = this.state.currentSearch2
      if (lastValue === value){
        if (t2 === AppConfig.SalesHeight){
          t2 = AppConfig.SalesLow
        }else {
          t2 = AppConfig.SalesHeight
        }
      }
      t = t2
    }
    if (value === 3 ){
      const lastValue = this.state.currentSearch2
      if (lastValue === value){
        if (t1 === AppConfig.PriceHeight){
          t1 = AppConfig.PriceLow
        }else {
          t1 = AppConfig.PriceHeight
        }
      }
      t = t1
    }
    this.setState({
      searchType2: t,
      currentSearch2:value,
      curPriceSearch:t1,
      curSaleSearch:t2
    },
      ()=>{

        this.sendSuperSearch(this.state.value)
      })
  }

  /**
   * 更多
   * */
  ToLowerEvent=()=>{
    //申请网络
    store.getSuperSearch(this.state.searchType1,this.state.searchType2,this.state.value,this.state.pageIndex).then(res=> {
      const data = this.state.searchData.concat(res.data)
      this.setState({
        renderPage1: false,
        searchData: data,
        pageIndex: res.pageIndex
      },()=>{
          this.refs.RefRecommend.RefData(true)
      });
    })
  }



  render1(){
    let status = null
    if (this.state.value !=='') {
      status = <Icon  onClick={this.onClear} size={17} className={'border-clear'} type='clear'/>
    } else {
      status = <View/>
    }
    const vStyleC = {
      height: 750,
    }
    const historyTab = this.state.history;
    return(
      <View>
        <View>
          <Text className={'search-searchText'} >热搜</Text>
          <View className={'hotContain'}>
            {
              store.keyWords.map((item1,index)=>{
                return(
                  <View key={index} className={'hotItemWidth'}>
                    <View onClick={()=>{
                      this.onClickHotItem(item1)
                    }} className={'hotItem'}>
                      <Text >{item1}</Text>
                    </View>
                  </View>
                );
              })
            }
          </View>

          {/*搜索历史*/}
          <View className={'search'}>
            <Text className={'search-searchText'}>搜索历史</Text>
            <AtIcon onClick={this.onClickClearHot} className={'search-deleteIcon'} value='trash' size='20' color='#666666'/>
          </View>

          <View className={'background'}>
            {/*搜索内容*/}
            <ScrollView
              style={vStyleC}
            >
              <View className={'searchContain'}>
                {
                  historyTab.map((item,key)=>{
                    return(
                      <View key={key} onClick={()=>{
                        this.onClickHistoryItem(item)
                      }} className={'searchItem'}>
                        <Text className={'searchItem-text'}>{item}</Text>
                      </View>
                    );
                  })
                }
              </View>
            </ScrollView>
          </View>


        </View>
      </View>
    );
  }

  render2(){
    const c1 =  process.env.TARO_ENV === 'h5'?"AtTabsClassH5":'';
    const tabList = appStore.appConfig.open >=1 ?
      [{ title : '淘宝' }, { title: '拼多多' }] :
      [{ title: '京东' }, { title: '拼多多' }]


    let t1 = this.state.curSaleSearch === AppConfig.SalesHeight?"高":"低"
    let t2 = this.state.curPriceSearch === AppConfig.PriceHeight?"高":"低"
    const secondTabList =[
      { title: '综合',   },
      { title: '最新', text: 'new'},
      { title: '销量',text:t1},
      { title: '价格',text:t2}
    ]

    const secondTab = (
      <View className={'secondTab'}>
        <AtTabBar
          className={c1}
          tabList={secondTabList}
          onClick={this.onClickSecond.bind(this)}
          current={this.state.currentSearch2 }
        >
        </AtTabBar>
      </View>
    );
    if (this.state.searchScrollviewHeight <=0) {
      taroUtils.GetScrollViewSurplusContain(this,".secondTab").then((h)=>{
        this.setState({
          searchScrollviewHeight:h
        })
      })
    }

    return (
      <View>
        <View>
          <AtTabs current={this.state.searchType1} tabList={tabList} onClick={this.onClickChosePage.bind(this)}>
            <AtTabsPane current={this.state.searchType1} index={AppConfig.TaoBao} >
              {/*<View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;' >淘宝</View>*/}
            </AtTabsPane>
            <AtTabsPane current={this.state.searchType1} index={AppConfig.JinDong}>
              {/*<View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>京东 </View>*/}
            </AtTabsPane>
            <AtTabsPane current={this.state.searchType1} index={AppConfig.PingDuoDuo}>
              {/*<View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>拼多多</View>*/}
            </AtTabsPane>

          </AtTabs>
          {secondTab}
        </View>
        <Recommend  ref={"RefRecommend"}  list={this.state.searchData} height={NumToPx(this.state.searchScrollviewHeight)} ToLowerEvent={this.ToLowerEvent} />

      </View>
    );
  }

  render () {

    let page = null
    if (this.state.renderPage1 === true){
      page = this.render1()
    }else {
      page = this.render2()
    }
    return (
      // <view className='page' style='height:{{clientHeight}};overflow:{{overflow}};'>
      <View className={'contain'}>
        <View className='hotSearch'>
          <View className='border'>
            <Icon  className={'border-img'} type='search'/>
            <Input value={this.state.value} onConfirm={this.onConfirm} onInput={this.onInput} className={'border-input'} ref={'hotInput'} placeholder={ appStore.appConfig.open >=1? '复制淘宝/京东/拼多多商品名称搜索':'搜索商品名称'} maxLength={50} />
            {status}
          </View>
          <Text className={'border-cancelText'} onClick={this.onSearch} >{'搜索'}</Text>
        </View>
        {page}
      </View>
    )
  }
}

export  default HotSearchPage
